//
//  Parser.m
//  CMS
//
//  Created by Vuong Van Khanh on 11/7/12.
//  Copyright (c) 2012 Rikkei. All rights reserved.
//

#import "Parser.h"
#import "StoreVars.h"
#import "xml_userDownload_writer.h"
#import "GDataXMLNode.h"
@implementation Parser

//check exist file director method
+ (NSString *)dataFilePath:(BOOL)forWrite {
    
    NSString *downloadDir = [StoreVars sharedInstance].downloadDir;
    if(!downloadDir){
        //create folder to store downloaded data from server
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
        NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
        NSString *downloadDir = [documentsDirectory stringByAppendingPathComponent:@"dataStore"];
        
        //Create folder
        if (![[NSFileManager defaultManager] fileExistsAtPath:downloadDir])
            [[NSFileManager defaultManager] createDirectoryAtPath:downloadDir withIntermediateDirectories:NO attributes:nil error:nil];
        [StoreVars sharedInstance].downloadDir = downloadDir;
        NSLog(@"create dataStore dir at write file");
    }
    NSString *documentsPath = [downloadDir
                               stringByAppendingPathComponent:@"userDownloaded.xml"];
    if (forWrite || 
        [[NSFileManager defaultManager] fileExistsAtPath:documentsPath]) {
        return documentsPath;
    } else {
        return [[NSBundle mainBundle] pathForResource:@"userDownloaded" ofType:@"xml"];
    }
    NSLog(@"documentsPath: %@", documentsPath);
}

+ (void)writeFile:(downloadInfo *)downloadInfo {
    
                                                        
    GDataXMLElement * downloadElement = [GDataXMLNode elementWithName:@"Downloaded"];
    
    for(xml_userDownload_writer *player in downloadInfo.downloader) {
        
        GDataXMLElement * userElement = 
        [GDataXMLNode elementWithName:@"username" stringValue:player.userId];
        GDataXMLElement * documentIdElement = 
        [GDataXMLNode elementWithName:@"contentId" stringValue:player.documentId];
        [downloadElement addChild:userElement];
        [downloadElement addChild:documentIdElement];
        
    }

    GDataXMLDocument *document;
    if([[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath:YES]]){
        NSData *xmlData = [[NSData alloc] initWithContentsOfFile:[self dataFilePath:YES]];
        document = [[GDataXMLDocument alloc] 
                                      initWithData:xmlData options:0 error:nil];
        NSLog(@"add data inside exits xml file");
//        GDataXMLElement * downloadElement = [GDataXMLNode elementWithName:@"Downloaded"];
        
        for(xml_userDownload_writer *writer in downloadInfo.downloader) {
            GDataXMLElement * userElement = 
            [GDataXMLNode elementWithName:@"userId" stringValue:writer.userId];
            GDataXMLElement * documentIdElement = 
            [GDataXMLNode elementWithName:@"documentId" stringValue:writer.documentId];
            
            [document.rootElement addChild:userElement];
            [document.rootElement addChild:documentIdElement];
        }
        
    }else{
        GDataXMLElement * downloadElement = [GDataXMLNode elementWithName:@"Downloaded"];
        
        for(xml_userDownload_writer *writer in downloadInfo.downloader) {
            
            GDataXMLElement * userElement = 
            [GDataXMLNode elementWithName:@"userId" stringValue:writer.userId];
            GDataXMLElement * documentIdElement = 
            [GDataXMLNode elementWithName:@"documentId" stringValue:writer.documentId];
            [downloadElement addChild:userElement];
            [downloadElement addChild:documentIdElement];
        }
        
        document = [[GDataXMLDocument alloc] 
                                      initWithRootElement:downloadElement];
        NSLog(@"add new xml data file");
        
    }
    
    NSData *xmlData = document.XMLData;
    
    NSString *filePath = [self dataFilePath:TRUE];
    NSLog(@"Saving xml data to %@...", filePath);
    [xmlData writeToFile:filePath atomically:YES];
    
}

+ (GDataXMLDocument *) loadParser:(NSString *) dataPath { 
    GDataXMLDocument *doc = nil;
    if([[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
        NSData *xmlData = [[NSMutableData alloc] initWithContentsOfFile:dataPath];
        NSError *error;
        doc = [[GDataXMLDocument alloc] initWithData:xmlData 
                                                               options:0 error:&error];
        if (doc == nil) { return nil; }
        
    }
    else{
        NSLog(@"Error! userDownloaded file not exist");
    }
    return doc;
}

@end
